package org.example.leetcpde;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class permute {

    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        dfs(new ArrayList<>(), nums, new boolean[nums.length], res);
        return res;
    }

    void dfs(List<Integer> state,
             int[] nums,
             boolean[] vidited,
             List<List<Integer>> res) {

        if (state.size() == nums.length) {
            res.add(new ArrayList<>(state));
            return;
        }

        Set<Integer> dup = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (vidited[i]) {
                continue;
            }
            int num = nums[i];
            if (dup.contains(num)) {
                continue;
            }

            dup.add(num);
            state.add(num);
            vidited[i] = true;
            dfs(state, nums, vidited, res);

            vidited[i] = false;
            state.remove(state.size() - 1);
        }
    }
}
